import { TeacherType } from "@/types";
import { ProTable } from "@ant-design/pro-components";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { Modal, Select } from "antd";
import { useEffect, useRef, useState } from "react";
import request from "@/services/interceptors";

interface TeacherSelectProps {
  value?: number[];
  onChange?: (value: number[]) => void;
  multiple?: boolean;
  initData?: TeacherType[];
}

const TeacherSelect: React.FC<TeacherSelectProps> = ({
  value = [],
  onChange,
  multiple = true,
  initData,
}) => {
  const [open, setOpen] = useState(false);
  const [selectedRows, setSelectedRows] = useState<TeacherType[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<number[]>(value || []);
  const actionRef = useRef<ActionType>(null);

  // 初始化已选数据
  useEffect(() => {
    if (initData.length) {
      setSelectedRows(initData);
      setSelectedKeys(initData.map((item) => item?.teacherId));
    }
  }, [initData]);

  // 处理选择变化
  const handleSelectionChange = (keys: any[], rows: TeacherType[]) => {
    if (multiple) {
      if (keys?.length > selectedRows?.length) {
        const newSelectedKey = keys.filter(
          (key) => !selectedKeys.find((item) => item === key)
        );
        const newSelected = rows.find(
          (row) => row?.teacherId === newSelectedKey[0]
        );
        setSelectedRows([...selectedRows, newSelected]);
      } else {
        const newSelectedKey = selectedKeys.filter(
          (key) => !keys.find((item) => item === key)
        );
        const newSelected = selectedRows.find(
          (row) => row?.teacherId === newSelectedKey[0]
        );
        selectedRows.splice(selectedRows.indexOf(newSelected), 1);
        setSelectedRows([...selectedRows]);
      }
    } else {
      setSelectedRows(rows);
    }
    // 合并当前页选中的数据
    setSelectedKeys(keys);
  };

  const columns: ProColumns<TeacherType>[] = [
    {
      title: "教师ID",
      dataIndex: "teacherId",
      hideInSearch: true,
    },
    {
      title: "教师用户名",
      dataIndex: "userName",
    },
    {
      title: "教师姓名",
      dataIndex: "realName",
    },
  ];
  console.log(selectedKeys, "selectedKeys");

  return (
    <>
      <Select
        placeholder="请选择教师"
        mode={multiple ? "multiple" : undefined}
        value={value}
        onChange={onChange}
        onClick={() => setOpen(true)}
        style={{ width: "100%" }}
        options={selectedRows.map((item) => ({
          label: `${item.realName}`,
          value: +item.teacherId,
        }))}
      />
      <Modal
        title="选择教师"
        open={open}
        onOk={() => {
          onChange?.(selectedKeys);
          setOpen(false);
        }}
        onCancel={() => setOpen(false)}
        width={800}
      >
        <ProTable<TeacherType>
          columns={columns}
          actionRef={actionRef}
          cardBordered
          options={false}
          rowKey="teacherId"
          rowSelection={{
            type: multiple ? "checkbox" : "radio",
            selectedRowKeys: selectedKeys,
            onChange: handleSelectionChange,
            preserveSelectedRowKeys: true, // 保持选中状态
          }}
          tableAlertRender={false}
          pagination={{ pageSize: 10 }}
          request={async (params) => {
            const res = await request.sgks.teacherListCreate({
              ...params,
              teacherStatus: "1",
              pageNo: params.current,
              pageSize: params.pageSize,
            } as any);
            return {
              data: res.data.records,
              total: res.data.totalCount,
            };
          }}
        />
      </Modal>
    </>
  );
};

export default TeacherSelect;
